package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.service.IPasswordManagementService;
import cn.wolfcode.util.JsonResult;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Service
public class PasswordManagementServiceImpl implements IPasswordManagementService {
    @Autowired
    private EmployeeMapper employeeMapper;

    // 重置密码
    @Override
    public JsonResult Reset(String newPassword, Long id) throws RuntimeException {
        // 获取当前登陆的用户的信息
        Employee currentUser = (Employee) SecurityUtils.getSubject().getPrincipal();
        // 通过当前登陆的用户名查询当前登陆用户信息
        // 验证是不是是管理员,是则执行重置
        if (employeeMapper.selectByName(currentUser.getName()).isAdmin()){
            //查询要重置的员工信息
            Employee ResetEmployee = employeeMapper.selectByPrimaryKey(id);
            //设置新密码(加盐加密,要重置的员工的name)
            ResetEmployee.setPassword(new Md5Hash(newPassword,ResetEmployee.getName()).toString());
            // 执行sql修改
            employeeMapper.updateByPassword(ResetEmployee);
            // 返回成功信息
            return new JsonResult(true,"重置成功");
        }else {
            // 不是超管则返回自定义异常
            return new JsonResult(false,"超级管理员才能操作");
        }
    }

    // 修改密码
    @Override
    public JsonResult update(String oldPassword, String newPassword) {
        // 获取当前登陆的用户的信息
        Employee currentUser = (Employee) SecurityUtils.getSubject().getPrincipal();
        //加密输入的原密码,使用当前登陆用户名作为加密的“盐”
        oldPassword = new Md5Hash(oldPassword,currentUser.getName()).toString();
        //根据真正的原密码然后比较
        if (!oldPassword.equals(currentUser.getPassword())){
            // 密码不正确返回
            return new JsonResult(false,"原密码错误");
        }else {
            // 旧密码正确,开始修改密码
            // 加密新密码设置进对象
            currentUser.setPassword(new Md5Hash(newPassword,currentUser.getName()).toString());
            // 执行sql修改
            employeeMapper.updateByPassword(currentUser);
            // 返回成功信息
            return new JsonResult(true,"修改成功");
        }
    }

}
